package sg.edu.nus.iss.billing.parse;
/**
 * @author sammil
 *
 */
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.HashMap;

public class TransactionHistoryState extends ParserState {
	
	private static final int MAX_LENGTH = 4 * Parser.MAX_LINE_LEN;
	public static final TransactionHistoryState SINGLETON = new TransactionHistoryState();

	private TransactionHistoryState() {

	}

	@Override
	public <L> ParserState parse(LineNumberReader in, HashMap<String,ArrayList<L>> transactionMap) throws IOException {

		System.out.println("In TransactionHistoryState at line " + in.getLineNumber());
		
		if (!TransactionHeaderParser.SINGLETON.parse(in, transactionMap)) {
			
			throw createException("Expected transaction header", in);
		}
		
		while (true) {
			in.mark(MAX_LENGTH);
			
			// try to parse a transaction record
			System.out.println("################try to parse a transaction record");
			if (!TransactionHistoryParser.SINGLETON.parse(in, transactionMap)) {
				
				// If we don't get a transaction then try to parse
				// SubscriptionHeader
				System.out.println("################try to parse a SubscriptionHeader record");
	
							
				if (!SubscriptionHeaderParser.SINGLETON.parse(in, transactionMap)){
					
					// If we don't get a SubscriptionHeader then try to parse
					// TransactionHeaderParser
					if (!TransactionHeaderParser.SINGLETON.parse(in, transactionMap)){
					
						// If we don't get a TransactionHeaderParser then try to parse
						// AccountHeaderParser
						System.out.println("################try to parse a AccountHeader record");
						if (!AccountHeaderParser.SINGLETON.parse(in, transactionMap)) {
							
							// If that didn't work then we must have finished
							return FinishedState.SINGLETON;
						}
						
						//return FinishedState.SINGLETON;
					}
				}
			}
		}
		
	}

}
